<?php
session_start();

// 如用户已经登录，直接点击此页面将跳转回主页
if (isset($_SESSION['user_id'])) {
    header('Location: index.php');
    exit;
}

// 处理登录逻辑
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['submit'])) {
    $username = trim($_POST['username']);
    $password = $_POST['password'];

    // 连接数据库
    $host = 'localhost';
    $db   = 'dev_community';
    $user = 'root'; // 请替换为您的数据库用户名
    $pass = 'root'; // 请替换为您的数据库密码
    $charset = 'utf8mb4';

    $dsn = "mysql:host=$host;dbname=$db;charset=$charset";
    $options = [
        PDO::ATTR_ERRMODE            => PDO::ERRMODE_EXCEPTION,
        PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
        PDO::ATTR_EMULATE_PREPARES   => false,
    ];

    try {
        $pdo = new PDO($dsn, $user, $pass, $options);
    } catch (\PDOException $e) {
        die("数据库连接失败: " . $e->getMessage());
    }

    // 检查用户名和密码
    $stmt = $pdo->prepare("SELECT * FROM users WHERE username = ?");
    $stmt->execute([$username]);
    $user = $stmt->fetch();

    if ($user && password_verify($password, $user['password'])) {
        // 登录成功，设置Session
        $_SESSION['user_id'] = $user['id'];
        // 可选：设置Cookie
        setcookie('user_id', $user['id'], time() + 3600); // 1小时后过期
        header('Location: index.php');
        exit;
    } else {
        // 登录失败，显示错误消息
        $error_message = "用户名或密码错误！";
    }
}
?>
<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link rel="stylesheet" type="text/css" href="./css/qs.css"/>
    <link rel="stylesheet" type="text/css" href="./css/lg.css"/>
    <title>智界论坛 - 用户登录</title>
</head>

<body>
    <div class="loginBox">
        <div class="header">
            <h2>智界论坛</h2>
            <a href="index.php" class="btn btn-link text-white">返回主页</a>
        </div>
        <form method="post" action="">
            <div class="item">
                <input type="text" name="username" required>
                <label for="username">用户名</label>
            </div>
            <div class="item">
                <input type="password" name="password" required>
                <label for="password">密码</label>
            </div>
            <div class="form-group">
                <button type="submit" name="submit" class="btn">登录
                    <span></span>
                    <span></span>
                    <span></span>
                    <span></span>
                </button>
            </div>
            <?php if (isset($error_message)): ?>
                <p class="error-message"><?php echo htmlspecialchars($error_message); ?></p>
            <?php endif; ?>
        </form>
    </div>

    <!-- 添加网页尾部 -->
<div class="footer">
    <p>&copy; 智界论坛·保留所有权利</p>
    <p>版权所有☆Qualan<sup>&copy;</sup> Q_L</p>
</div>
</body>

</html>